package com.shqcjd.preinstallmobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.google.gson.Gson;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.AbnormalBean;
import com.shqcjd.preinstallmobile.model.pojo.EquipmentInspectionBean;
import com.shqcjd.preinstallmobile.model.pojo.ImgBean;
import com.shqcjd.preinstallmobile.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallmobile.model.pojo.UploadException;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.AlbumUtils;
import com.shqcjd.preinstallmobile.util.Config;
import com.shqcjd.preinstallmobile.util.MyGlideEngine;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;
import com.shqcjd.preinstallmobile.widget.AbnormalDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class EquipmentInspectionActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.ll_equipment_inspection)
    LinearLayout llEquipmentInspection;
    @BindView(R.id.cb_equiment)
    CheckBox cbEquiment;
    @BindView(R.id.tv_equipment_inspection_last)
    TextView tvEquipmentInspectionLast;
    @BindView(R.id.btn_equipment_inspection_guidance)
    Button btnEquipmentInspectionGuidance;
    @BindView(R.id.tv_equipment_inspection_next)
    TextView tvEquipmentInspectionNext;
    @BindView(R.id.sv_equment_inspection)
    ScrollView svEqumentInspection;


    private Context context;
    private final int IMAGE_FILE_RESULT_CODE = 2;
    private AbnormalDialog abnormalDialog;
    private int tId;
    private String kks = "";
    private String lastKks = "";
    private String nextKks = "";
    private int epId;

    private HashMap<Integer, RadioButton> mChildTrueList = new HashMap<>();
    private HashMap<Integer, RadioButton> mChildFalseList = new HashMap<>();
    private HashMap<Integer, EditText> mChildNumList = new HashMap<>();
    private List<RadioGroup> mChildRadioGroupList = new ArrayList<>();

    private int colorCid = -1;
    private int numCid = -1;
    private static final int REQUEST_CODE = 100;

    private static final int REQUEST_QCODE_CODE = 110;
    private static final int REQUEST_COLOR_CODE = 111;

    private final int COMMIT_TIME = 2;//2秒钟没有输入文字 就自动提交
    private int timer = 3;

    private EquipmentInspectionBean.PartsBean.ItemsBean iBean;
    private EquipmentInspectionBean.PartsBean.ItemsBean.MyBean itemBean;


    private Handler handler = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            timer++;
            if (timer == COMMIT_TIME) {
                edChildValue = mChildNumList.get(numCid); 
                int rStatus = 1;
                EditText editText = mChildNumList.get(numCid);
                RadioButton rb1 = (RadioButton) mChildTrueList.get(numCid);
                RadioButton rb2 = (RadioButton) mChildFalseList.get(numCid);
                if (rb1.isChecked()) {
                    rStatus = 1;
                } else {
                    rStatus = -1;
                }
                putCheckResultHttp(edChildValue == null ? "" : edChildValue.getText().toString(), rStatus, numCid);
            }
            handler.postDelayed(r, 1000);
        }
    };

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_inspection;
    }

    @Override
    public void init() {
        super.init();
        Context mContext = this;
        tId = getIntent().getIntExtra("tId", 1);
        kks = getIntent().getStringExtra("kks");
        handler.postDelayed(r, 1000);
//        tId = 32;
//        kks = "%23100000";
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView() {
        super.initView();
        context = this;
        cbEquiment.setVisibility(View.VISIBLE);

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });

        btnEquipmentInspectionGuidance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ExpertListActivity.class);
                intent.putExtra("expertType",0);
                intent.putExtra("equipmentId",epId);
                intent.putExtra("TaskId",tId);
                startActivity(intent);
            }
        });

        tvEquipmentInspectionLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(lastKks.equals("")){
                    Toast.makeText(context, "当前已经是第一条", Toast.LENGTH_SHORT).show();
                }else{
                    kks = lastKks;
                    isInspectionData(lastKks);
                }
//                refreshView();
            }
        });

        tvEquipmentInspectionNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(nextKks.equals("")){
                    Toast.makeText(context, "当前已经是最后一条", Toast.LENGTH_SHORT).show();
                }else{
                    kks = nextKks;
                    isInspectionData(nextKks);
                }
//                refreshView();
            }
        });

        cbEquiment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                openOrCloseSwitchHttp();
            }
        });

        getData();
    }

    EditText edChildValue = null;
    private int position = 0;

    private void initListView(List<EquipmentInspectionBean.PartsBean> mList) {
        for (EquipmentInspectionBean.PartsBean p : mList) {
            position=0;
            View v = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_title, null);
            TextView title = v.findViewById(R.id.tv_title);
            title.setText(p.part_name);
            llEquipmentInspection.addView(v);
            for (EquipmentInspectionBean.PartsBean.ItemsBean c : p.items) {
                position++;
                View vChild;
                TextView childTitle;
                TextView chileStandard;
                TextView childState;
                TextView childCode;
                RadioButton childTrue, childFalse;
                RadioGroup childRg;
                if (c.check_method.size() == 0) {
                    vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_common, null);
                } else {
                    if (c.check_type == 1) {
                        vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_color, null);
                    } else {
                        vChild = LayoutInflater.from(context).inflate(R.layout.item_equipment_inspect_number, null);
                        edChildValue = vChild.findViewById(R.id.ed_child_value);
                        mChildNumList.put(c.id, edChildValue);
                        if(!c.value.equals("-1")){
                            edChildValue.setText(c.value+"");
                        }
                        edChildValue.setTag(c.id);
                        edChildValue.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                numCid = c.id;
                                if (s.toString().equals("")) {
                                    return;
                                }
                                timer = 0;
                                if (Double.parseDouble(c.min) <= Double.parseDouble(s.toString()) && Double.parseDouble(s.toString()) <= Double.parseDouble(c.max)) {
                                    RadioButton rb = mChildTrueList.get(c.id);
                                    rb.setChecked(true);
                                } else {
                                    RadioButton rb = mChildFalseList.get(c.id);
                                    rb.setChecked(true);
                                }
                            }
                        });
                    }
                    if (edChildValue != null) {
                        edChildValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                            @Override
                            public void onFocusChange(View v, boolean hasFocus) {
                                if (hasFocus) {
                                    numCid = c.id;
                                }
                            }
                        });
                    }


                    Button btn_chile_color = vChild.findViewById(R.id.btn_chile_color);
                    Button btn_chile_number = vChild.findViewById(R.id.btn_chile_number);
                    Button btn_chile_qcode = vChild.findViewById(R.id.btn_chile_qcode);
                    for (int k = 0; k < c.check_method.size(); k++) {
                        if (c.check_method.get(k).type == 5) {
                            btn_chile_color.setVisibility(View.VISIBLE);
                        }
                        if (c.check_method.get(k).type == 3) {
                            btn_chile_number.setVisibility(View.VISIBLE);
                        }
                        if (c.check_method.get(k).type == 4) {
                            btn_chile_qcode.setVisibility(View.VISIBLE);
                            btn_chile_qcode.setTag(c.check_method.get(k));
                        }
                    }
                    btn_chile_number.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                    btn_chile_color.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            colorCid = c.id;
                            checkPermissions();
                        }
                    });
                    btn_chile_qcode.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            numCid = c.id;
                            iBean = c;
                            itemBean = (EquipmentInspectionBean.PartsBean.ItemsBean.MyBean) v.getTag();
                            if(itemBean.data.equals("")){
                                Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            RxPermissions permissions = new RxPermissions(EquipmentInspectionActivity.this);
                            permissions.setLogging(true);
                            permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            if (aBoolean) {
                                                startActivityForResult(new Intent(EquipmentInspectionActivity.this, QRcodeActivity.class),REQUEST_QCODE_CODE);
                                            } else {
                                                ToastUtils.show(EquipmentInspectionActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                            }
                                        }
                                    });
                        }
                    });
                }
                childTitle = vChild.findViewById(R.id.tv_child_title);
                chileStandard = vChild.findViewById(R.id.tv_child_standard);
                childState = vChild.findViewById(R.id.tv_child_state);
                childTrue = vChild.findViewById(R.id.rb_child_state_true);
                childFalse = vChild.findViewById(R.id.rb_child_state_false);
                childRg = vChild.findViewById(R.id.rg_child_state);
                childCode = vChild.findViewById(R.id.tv_child_code);

                childCode.setText(position+"");
                childTitle.setText(c.name);
                if(c.last_result==1){
                    childState.setText("正常");
                }else if(c.last_result==2){
                    childState.setText("异常");
                }
                chileStandard.setText(c.stand);
                if(c.result==1){
                    childTrue.setChecked(true);
                }else if(c.result==2){
                    childFalse.setChecked(true);
                }
                llEquipmentInspection.addView(vChild);
                mChildTrueList.put(c.id, childTrue);
                mChildFalseList.put(c.id, childFalse);
                mChildRadioGroupList.add(childRg);
                childRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.rb_child_state_true:
                                putCheckResultHttp(mChildNumList.get(c.id) == null ? "" : mChildNumList.get(c.id).getText().toString(), 1, c.id);
                                break;
                            case R.id.rb_child_state_false:
                                putCheckResultHttp(mChildNumList.get(c.id) == null ? "" : mChildNumList.get(c.id).getText().toString(), -1, c.id);
                                break;
                        }
                    }
                });
            }
        }
    }

    private void isInspectionData(String kksStr){
        ApiService.intentEquipmentHttp(kksStr, tId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取巡检信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if(responseData.retCode==10000){
                            if(responseData.data.check_gps){
                                RxPermissions permissions = new RxPermissions(EquipmentInspectionActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if(distance<Config.INSPECTION_DISTANCE){
                                                                if(responseData.data.isgroup){
                                                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", tId);
                                                                    startActivity(it);
                                                                }else{
                                                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", tId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                                finish();
                                                            }else{
                                                                Toast.makeText(context, "当前位置距离巡检点超过了"+Config.INSPECTION_DISTANCE+"米", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(EquipmentInspectionActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });
                            }else{
                                if(responseData.data.isgroup){
                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", tId);
                                    startActivity(it);
                                }else{
                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                    it.putExtra("tId", tId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                                finish();
                            }
                        }else{
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    /**
     * 上传多图
     * @param mList
     * @param prid
     */
    private void loadMultiFile(List<ImgBean> mList, Integer prid) {
        //上传图片的时候  把本地图片拿出来上传  然后上传成功之后 把上传成功的图片和网络图片合体
        List<File> files = new ArrayList<>();
        for (ImgBean uri : mList) {
            if(uri.isLocal){
                files.add(new File(uri.url));
            }
        }
        if(files.size()==0){
            List<String> l = new ArrayList<>();
            for(int i=0; i<mList.size(); i++){
                if(!mList.get(i).isLocal){
                    l.add(mList.get(i).url);
                }
            }
            putExceptionInfo(l,prid);
        }else{
            ApiService.uploadMultiImg(files)
                    .compose(RxSchedulersHelper.io_main())
                    .subscribe(new RxObserver<ResponseData<List<String>>>() {
                        @Override
                        public void _onSubscribe(Disposable d) {
                            super._onSubscribe(d);
                            showWaitingDialog("上传图片中");
                        }

                        @Override
                        public void _onNext(ResponseData<List<String>> retData) {
                            if (retData.retCode == 10000) {
                                List<String> list = retData.data;
                                for(int i=0; i<mList.size(); i++){
                                    if(!mList.get(i).isLocal){
                                        list.add(mList.get(i).url);
                                    }
                                }
                                putExceptionInfo(list,prid);
                            } else {
                                ToastUtils.showShort(context,"上传失败");
                            }
                        }

                        @Override
                        public void _onError(String errorMessage) {
                            hideWaitingDialog();
                            ToastUtils.showShort(context,errorMessage);
                        }

                        @Override
                        public void _onComplete() {
                            super._onComplete();
                            hideWaitingDialog();
                        }
                    });
        }

    }

    /**
     * 添加或修改巡检异常描述
     * @param data
     * @param prid
     */
    private void putExceptionInfo(List<String> data, Integer prid) {
        String info = abnormalDialog.et_dialog_abnormal.getText().toString();
        UploadException uploadException = new UploadException();
        uploadException.patrol_record_id=prid;
        uploadException.info = info;
        uploadException.imgs = data;
        String json = new Gson().toJson(uploadException);

        ApiService.putCheckException(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传异常信息");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData.retCode == 10000) {
                            abnormalDialog.dismiss();
                            ToastUtils.showShort(context,"提交成功");
                        } else {
                            ToastUtils.showShort(context,"提交信息失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context,errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });

    }

    /**
     * 显示异常图片上传对话框
     */
    int p ;
    private void showUploadDialog(Integer prid, String str, List<ImgBean> img, String solution) {
         p = prid;
        if(abnormalDialog==null){
            abnormalDialog = new AbnormalDialog(context);
            abnormalDialog.setOnBtnClickListener(new AbnormalDialog.OnBtnClickListener() {
                @Override
                public void onBtnClick(View view, List<ImgBean> mList) {
                    if (mList.size() > 0) {
                        loadMultiFile(mList,p);
                    }else{
                        Toast.makeText(context, "请上传异常图片", Toast.LENGTH_SHORT).show();
                    }

                    }
                });
            abnormalDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    abnormalDialog.clearDialogView();
                    nextInspect();
                }
            });
            }
        if(!abnormalDialog.isShowing()){
            abnormalDialog.show();
            abnormalDialog.setAbnormalInfo(str, img, solution);
        }
    }

    /**
     * 判断所有的radiobutton有没有被选中
     *
     * @return
     */
    private boolean isCheckAll() {
        for (int i = 0; i < mChildRadioGroupList.size(); i++) {
            RadioGroup radioGroup = mChildRadioGroupList.get(i);
            RadioButton rb1 = (RadioButton) radioGroup.getChildAt(0);
            RadioButton rb2 = (RadioButton) radioGroup.getChildAt(1);
            if (!rb1.isChecked() && !rb2.isChecked()) {
                return false;
            }
        }
        return true;
    }


    private void getData() {
        ApiService.equipmentInspectionHttp(tId, kks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentInspectionBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentInspectionBean> responseData) {
                        if (responseData.retCode != 10000) {
                            return;
                        }
                        lastKks = responseData.data.prev.kks;
                        nextKks = responseData.data.next.kks;
                        cbEquiment.setChecked(responseData.data.running);
                        if(nextKks.equals("")){
                            tvEquipmentInspectionNext.setText("当前已经是最后一个");
                        }else{
                            tvEquipmentInspectionNext.setText("下一个/ " + responseData.data.next.name);
                        }

                        if(lastKks.equals("")){
                            tvEquipmentInspectionLast.setText("当前已经是第一个");
                        }else{
                            tvEquipmentInspectionLast.setText("上一个/ " + responseData.data.prev.name);
                        }
                        epId = responseData.data.id;
                        tvIncludeTitle.setText(responseData.data.name);
                        initListView(responseData.data.parts);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void getButtonData(String url, String type,int equipment_part_item_id, EquipmentInspectionBean.PartsBean.ItemsBean mBean) {
        ApiService.equipmentInspectionButtonHttp(url, epId, type,equipment_part_item_id)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<String> responseData) {
                        if (responseData.retCode != 10000) {
                            hideWaitingDialog();
                            return;
                        }
                        if(responseData.data.equals("")){
                            return;
                        }
                        EditText editText = mChildNumList.get(numCid);
                        editText.setText(responseData.data);
                        Double max = Double.parseDouble(mBean.max);
                        Double min = Double.parseDouble(mBean.min);
                        Double num = Double.parseDouble(responseData.data);
                        if (min <= num && num <= max) {
                            RadioButton rb = mChildTrueList.get(numCid);
                            rb.setChecked(true);
                        } else {
                            RadioButton rb = mChildFalseList.get(numCid);
                            rb.setChecked(true);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void nextInspect(){
        if (isCheckAll()) {
            if(!nextKks.equals("")){
                isInspectionData(nextKks);
            }else{
                finish();
                Toast.makeText(context, "所有设备巡检完毕", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void putCheckResultHttp(String value, int status, int eId) {
        Map<String, String> map = new HashMap<>();
        map.put("task_id", tId + "");
        map.put("equipment_part_item_id", eId + "");
        map.put("value", value);
        map.put("status", status + "");
        map.put("equipment_id", epId + "");

        ApiService.putCheckResultHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> responseData) {
                        if (responseData.retCode == 10000) {
                            if (status==-1) {
                                getAbnormalInfoHttp(tId, epId, eId, value, responseData.data);
                            }else{
                                nextInspect();
                            }

                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getAbnormalInfoHttp(int task_id, int equipment_id, int equipment_part_item_id, String value, int prId) {
        ApiService.getAbnormalInfo(task_id, equipment_id, equipment_part_item_id, value)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<AbnormalBean> responseData) {
                        if (responseData.retCode == 10000) {
                            List<ImgBean> list = new ArrayList<>();
                            for(int i=0; i<responseData.data.imgs.size(); i++){
                                list.add(new ImgBean(responseData.data.imgs.get(i), false));
                            }
                            showUploadDialog(prId, responseData.data.exception_description, list, responseData.data.solution_description);
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    private void openOrCloseSwitchHttp() {
        ApiService.openOrCloseSwitchHttp(kks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode != 10000) {
                            hideWaitingDialog();
                            return;
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(EquipmentInspectionActivity.this)
                                    .choose(MimeType.allOf()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(6) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        abnormalDialog.addPic(new ImgBean(albumStringPath, true));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode && numCid != -1) {
            String value = data.getStringExtra("qr_code_key");
            EditText editText = mChildNumList.get(numCid);
            editText.setText(value);
        }
        if (resultCode == REQUEST_COLOR_CODE && colorCid != -1) {
            String result = data.getStringExtra("result");
            if (result.equals("异常")) {
                RadioButton r = mChildFalseList.get(colorCid);
                r.setChecked(true);
            } else {
                RadioButton r = mChildTrueList.get(colorCid);
                r.setChecked(true);
            }
        }

        if (REQUEST_QCODE_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            if(value.equals(kks)){
                getButtonData(itemBean.data, iBean.data_type, itemBean.equipment_part_item_id, iBean);
            }else{
                Toast.makeText(context, "设备二维码有误，请确认后重新扫描", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void checkPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Intent it = new Intent(context, ColorActivity.class);
                            startActivityForResult(it, REQUEST_COLOR_CODE);
                        } else {

                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (r != null) {
            handler.removeCallbacks(r);
        }
    }
}
